<template>
  <div class="voice-recorder">
    <img
      @touchstart="startRecording"
      @touchend="stopRecording"
      @mousedown="startRecording"
      @mouseup="stopRecording"
      @mouseleave="stopRecording"
      class="speak"
      :title="isRecording ? '松开结束' : '按住说话'"
     
    />

    <div v-if="isRecording" class="recording-indicator">
      <div class="volume-indicator" :style="{ height: volume + '%' }"></div>
      <p style="color: #fff">录音中...</p>
    </div>
    <!-- <audio v-if="audioUrl" :src="audioUrl" controls></audio> -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      isRecording: false,
      mediaRecorder: null,
      audioChunks: [],
      audioUrl: "",
      volume: 50, // 模拟音量
      volumeInterval: null,
    };
  },
  methods: {
    async startRecording() {
      this.isRecording = true;
      this.audioChunks = [];

      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: true,
        });
        this.mediaRecorder = new MediaRecorder(stream);

        this.mediaRecorder.ondataavailable = (event) => {
          this.audioChunks.push(event.data);
        };

        this.mediaRecorder.onstop = () => {
          const audioBlob = new Blob(this.audioChunks, { type: "audio/wav" });
          this.audioUrl = URL.createObjectURL(audioBlob);
          // this.$emit("record-complete", audioBlob);
          this.$emit("record-complete", this.audioUrl);

          // 停止所有音轨
          stream.getTracks().forEach((track) => track.stop());
        };

        this.mediaRecorder.start();

        // 模拟音量变化
        this.volumeInterval = setInterval(() => {
          this.volume = 30 + Math.random() * 70;
        }, 100);
      } catch (error) {
        console.error("录音失败:", error);
        this.isRecording = false;
        this.$emit("record-error", error);
      }
    },

    stopRecording() {
      if (!this.isRecording) return;

      this.isRecording = false;
      clearInterval(this.volumeInterval);

      if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
        this.mediaRecorder.stop();
      }
    },
  },

  beforeDestroy() {
    if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
      this.mediaRecorder.stop();
    }
    clearInterval(this.volumeInterval);
  },
};
</script>

<style scoped>
.voice-recorder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.record-button {
  padding: 10px 20px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  width: 150px;
  height: 50px;
}

.record-button:active {
  background-color: #06ad56;
}

.recording-indicator {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.volume-indicator {
  width: 30px;
  background-color: #07c160;
  margin-bottom: 10px;
  transition: height 0.1s;
}

audio {
  margin-top: 20px;
}
</style>